package jwt

import (
	"fmt"
	"time"

	"github.com/spf13/viper"

	jwt "github.com/dgrijalva/jwt-go"
)

type Claims struct {
	UserId   int64  `json:"user_id"`
	Username string `json:"username"`
	jwt.StandardClaims
}

func GenerateToken(userId int64, username string) (string, error) {
	var (
		JwtSecret     = []byte(viper.GetString("app.JwtSecret"))
		JwtExpiresAt  = viper.GetDuration("app.JwtExpiresAt")
		SigningMethod = viper.GetString("app.SigningMethod")
	)
	nowTime := time.Now()
	expireTime := nowTime.Add(JwtExpiresAt * time.Hour)
	fmt.Printf("jwt过期时间为%v\n", JwtExpiresAt)
	fmt.Println("jwt 过期时间为", expireTime.Unix())
	claims := Claims{
		userId,
		username,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "go-api",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.GetSigningMethod(SigningMethod), claims)
	token, err := tokenClaims.SignedString(JwtSecret)

	return token, err
}

func ParseToken(token string) (*Claims, error) {
	JwtSecret := []byte(viper.GetString("app.JwtSecret"))

	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return JwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
